﻿using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using WebIM.API.Common.Models;
using WebIM.API.Thirdparty.Easemob;
using WebIM.API.Thirdparty.Easemob.Models;

namespace WebIM.API.Controllers
{
    /// <summary>
    /// IM 用户信息接口
    /// </summary>
    [ApiController]
    [Route("/users")]
    public class ImUserController : ControllerBase
    {
        private readonly IEasemobSettings _eSettings;
        private readonly IEasemobApi _easemobApi;
        private readonly ILogger<ImUserController> _logger;

        /// <inheritdoc />
        public ImUserController(IEasemobSettings settings, IEasemobApi easemobApi, ILogger<ImUserController> logger)
        {
            _eSettings = settings;
            _easemobApi = easemobApi;
            _logger = logger;
        }

        /// <summary>
        /// 注册环信
        /// </summary>
        /// <param name="input">input</param>
        /// <returns>output</returns>
        [HttpPost]
        [Route("register")]
        [Produces("application/json")]
        public async Task<MessageCodeResult<RegisterUserOutput>> RegisterUser([FromBody] RegisterUserInput input)
        {
            var response = await _easemobApi.RegisterUser(_eSettings.OrgName, _eSettings.AppName, input);
            if (response.IsSuccessStatusCode)
            {
                return MessageCodeResult<RegisterUserOutput>.Ok(response.Content);
            }

            if (response.Error != null)
            {
                var desc = await response.Error.GetContentAsAsync<IDictionary<string, object>>();
                var message = EasemobErrorUtils.ResolveUserErrorMessage(desc);
                _logger.LogError("环信接口返回错误: {0}", message);
                return MessageCodeResult<RegisterUserOutput>.Fail(message);
            }

            return MessageCodeResult<RegisterUserOutput>.Fail("远程接口调用出错");
        }
    }
}